package com.shijie.service;

import java.util.List;

import javax.annotation.Resource;

import com.shijie.domain.entity.Magazines;
import com.shijie.mapper.MagazinesMapper;
import com.shijie.mapper.ProductsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import tk.mybatis.mapper.entity.Example;

import com.shijie.core.AbstractService;
import com.shijie.domain.entity.UserComments;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.domain.enums.EnumInterface.EntityType;
import com.shijie.mapper.UserCommentsMapper;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class UserCommentsService extends AbstractService<UserComments> {

	@Resource
	private UserCommentsMapper userCommentsMapper;

    @Resource
    private ProductsMapper productsMapper;

    @Resource
    private MagazinesMapper magazinesMapper;

    public List<UserComments> queryCommentsByIdAndType(Integer entityId, EntityType entityType) {
        Assert.notNull(entityId, "实体ID不能为空！");
        Assert.notNull(entityType, "实体类型不能为空！");
        Example condition = new Example(UserComments.class);
        condition.createCriteria().andEqualTo("entityId", entityId).andEqualTo("entityType", entityType.ordinal());
        condition.orderBy("commentTime").asc();
        return userCommentsMapper.selectByCondition(condition);
    }

    /**
     * 增加评论
     * @param userComments
     */
	@Transactional
	public void save(UserComments userComments) {
        userCommentsMapper.insertSelective(userComments);
        // 增加对应的评论数
        if (EntityType.MAGAZINES.equals(userComments.getEntityType()) ||
                EntityType.ACTIVITY.equals(userComments.getEntityType()) ||
                EntityType.TALENT_ARTICLE.equals(userComments.getEntityType())) {

            Magazines magazine = magazinesMapper.selectByPrimaryKey(userComments.getEntityId());
            if (magazine != null) {
                Magazines update = new Magazines();
                update.setId(magazine.getId());
                update.setComments(magazine.getComments() + 1);
                magazinesMapper.updateByPrimaryKeySelective(update);
            }
        }
    }

}
